<template>
  <div class="user-form">
    <h2>{{ title }}</h2>
    <form @submit.prevent="handleSubmit">
      <div class="form-group">
        <label for="username">用户名:</label>
        <input id="username" v-model="form.username" type="text" required />
      </div>

      <div class="form-group">
        <label for="email">电子邮箱:</label>
        <input id="email" v-model="form.email" type="email" required />
      </div>

      <div class="form-group">
        <label for="age">年龄:</label>
        <input id="age" v-model.number="form.age" type="number" min="1" max="120" />
      </div>

      <div class="form-group">
        <label>
          <input v-model="form.subscribe" type="checkbox" />
          订阅新闻通讯
        </label>
      </div>

      <div class="form-group">
        <button type="submit">提交</button>
        <button type="button" @click="resetForm">重置</button>
      </div>
    </form>
  </div>
</template>

<script setup lang="ts">
  import { ref, defineProps, defineEmits } from 'vue'

  defineProps({
    title: {
      type: String,
      default: '用户表单'
    }
  })

  const emit = defineEmits(['submit'])

  const form = ref({
    username: '',
    email: '',
    age: 18,
    subscribe: false
  })

  function handleSubmit() {
    emit('submit', { ...form.value })
  }

  function resetForm() {
    form.value = {
      username: '',
      email: '',
      age: 18,
      subscribe: false
    }
  }
</script>

<style scoped>
  .user-form {
    max-width: 500px;
    margin: 0 auto;
    padding: 20px;
    border: 1px solid #ddd;
    border-radius: 8px;
    background-color: #f9f9f9;
  }

  .form-group {
    margin-bottom: 15px;
  }

  label {
    display: block;
    margin-bottom: 5px;
    font-weight: bold;
  }

  input[type='text'],
  input[type='email'],
  input[type='number'] {
    width: 100%;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
  }

  button {
    padding: 8px 16px;
    margin-right: 10px;
    background-color: #4caf50;
    color: #fff;
    border: 0;
    border-radius: 4px;
    cursor: pointer;
  }

  button[type='button'] {
    background-color: #f44336;
  }

  button:hover {
    opacity: 0.9;
  }
</style>
